<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

interface User {
  id: number;
  username: string;
  email: string;
  status: 'active' | 'inactive';
  createdAt: string;
  lastLogin: string;
}

const loading = ref(false);
const showAddDialog = ref(false);
const isEdit = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const userFormRef = ref();

const searchForm = reactive({
  username: '',
  status: '',
});

const userForm = reactive({
  id: 0,
  username: '',
  email: '',
  password: '',
  status: 'active',
});

const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
};

const userList = ref<User[]>([
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    status: 'active',
    createdAt: '2024-01-01 10:00:00',
    lastLogin: '2024-01-15 14:30:00',
  },
  {
    id: 2,
    username: 'user001',
    email: 'user001@example.com',
    status: 'active',
    createdAt: '2024-01-02 11:00:00',
    lastLogin: '2024-01-15 13:20:00',
  },
  {
    id: 3,
    username: 'user002',
    email: 'user002@example.com',
    status: 'inactive',
    createdAt: '2024-01-03 12:00:00',
    lastLogin: '2024-01-10 09:15:00',
  },
]);

onMounted(() => {
  total.value = userList.value.length;
});

const handleSearch = () => {
  // 实现搜索逻辑
  ElMessage.success('搜索功能待实现');
};

const resetSearch = () => {
  searchForm.username = '';
  searchForm.status = '';
};

const handleEdit = (row: User) => {
  isEdit.value = true;
  userForm.id = row.id;
  userForm.username = row.username;
  userForm.email = row.email;
  userForm.status = row.status;
  showAddDialog.value = true;
};

const handleToggleStatus = (row: User) => {
  const action = row.status === 'active' ? '禁用' : '启用';
  ElMessageBox.confirm(`确定要${action}用户 "${row.username}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    row.status = row.status === 'active' ? 'inactive' : 'active';
    ElMessage.success(`${action}成功`);
  });
};

const handleDelete = (row: User) => {
  ElMessageBox.confirm(`确定要删除用户 "${row.username}" 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const index = userList.value.findIndex((user) => user.id === row.id);
    if (index > -1) {
      userList.value.splice(index, 1);
      total.value = userList.value.length;
      ElMessage.success('删除成功');
    }
  });
};

const handleSubmit = () => {
  userFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑用户
        const index = userList.value.findIndex(
          (user) => user.id === userForm.id,
        );
        if (index > -1) {
          userList.value[index] = {
            ...userList.value[index],
            ...userForm,
          } as User;
          ElMessage.success('编辑成功');
        }
      } else {
        // 添加用户
        const newUser: User = {
          id: Date.now(),
          username: userForm.username,
          email: userForm.email,
          status: userForm.status as 'active' | 'inactive',
          createdAt: new Date().toLocaleString(),
          lastLogin: '-',
        };
        userList.value.push(newUser);
        total.value = userList.value.length;
        ElMessage.success('添加成功');
      }
      showAddDialog.value = false;
      resetUserForm();
    }
  });
};

const resetUserForm = () => {
  userForm.id = 0;
  userForm.username = '';
  userForm.email = '';
  userForm.password = '';
  userForm.status = 'active';
  isEdit.value = false;
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};
</script>

<template>
  <div class="users">
    <div class="page-header">
      <h1 class="page-title">用户管理</h1>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加用户
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card>
      <el-table v-loading="loading" :data="userList" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="180" />
        <el-table-column prop="lastLogin" label="最后登录" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              size="small"
              :type="row.status === 'active' ? 'danger' : 'success'"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="isEdit ? '编辑用户' : '添加用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.users {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style>
